<template>
  <div class="base-container" style="display: flex">
<!--    <t-row :gutter="14" style="height: 100%">-->
    <div style="position: fixed;width: 20%;height: 100%;overflow: scroll;padding-bottom: 100px">

<!--      <t-col :span="3" >-->
        <t-input
          style="margin-bottom: 10px"
          clearable
          placeholder="请输入单位名称"
          v-model="deptName"
          @change="deptNameTreeFilter"
        >
          <template #prefix-icon>
            <t-icon name="search" class="icon" size="16"/>
          </template>
        </t-input>
        <t-tree activable ref="tree" @active="onActive" :value.sync="deptNameTreeValue" :data="deptOptions" :keys="{value:'id'}" @click="handleNodeClick" :expandAll="false" :filter="filterByText" hover :expand-on-click-node="false"  />
<!--      </t-col>-->
      </div>
    <div style="margin-left: 24%;border-left: 1px solid #E5E6EB;padding-left: 10px">
<!--      <t-col :span="9"  style="border-left: 1px solid #E5E6EB;height: 100%">-->
        <t-form ref="form" :data="queryParams" label-width="80" @reset="onReset" @submit="()=>{this.pagination.current=1;this.queryParams.pageNum=1;this.getList()}">

          <t-row style="border-bottom: 1px solid #E5E6EB;margin-bottom: 10px">
            <t-col :span="11" class="query-form-inline">
              <t-form-item label="登录名称" name="userName">
                <t-input
                  v-model="queryParams.userName"
                  clearable
                  placeholder="请输入用户名称"
                  style="width: 240px"
                />
              </t-form-item>
              <t-form-item label="用户名称" name="nickName">
                <t-input
                  v-model="queryParams.nickName"
                  clearable
                  placeholder="请输入用户名称"
                  style="width: 240px"
                />
              </t-form-item>
              <t-form-item label="手机号码" name="phonenumber">
                <t-input
                  v-model="queryParams.phonenumber"
                  clearable
                  placeholder="请输入手机号码"
                  style="width: 240px"
                />
              </t-form-item>
              <t-form-item label="状态" name="status">
                <t-select style="width: 240px" placeholder="用户状态" :options="dict.type.sys_normal_disable" v-model="queryParams.status">
<!--                  <t-option v-for="(item, index) in dict.type.sys_normal_disable" :value="item.value" :label="item.label" :key="index">-->
<!--                    {{ item.label }}-->
<!--                  </t-option>-->
                </t-select>
              </t-form-item>
<!--              <t-form-item label="创建时间" name="status">-->
<!--                <t-date-range-picker v-model="queryParams.dateRange" :placeholder="['开始时间','结束时间']"  clearable/>-->
<!--              </t-form-item>-->
            </t-col>
            <t-col :span="1" class="operation-container">
              <t-button theme="primary" type="submit">查询</t-button>
              <t-button theme="default" variant="outline" type="reset">重置</t-button>
            </t-col>
          </t-row>
        </t-form>
        <div class="btn-group-inline">
          <t-button   @click="dialog.open_add_edit_user = true;dialog.header='添加用户';dialog.userId=0" variant="outline" theme="primary">
            <t-icon name="add" slot="icon"/>
            新增
          </t-button>
        </div>
        <t-table
          rowKey="id"
          :data="data"
          :columns="columns"
          hover
          :pagination="pagination"
          :loading="dataLoading"
        >
          <template #roles="{ row }">
            <template v-for="(item,index) in row.roles">
              {{item.roleName}}{{index+1===row.roles.length?'':'、'}}
            </template>
          </template>
          <template #status="{ row }">
            <t-switch @change="handleStatusChange(row)" :value="row.status==='0'?true:false">
            </t-switch>
          </template>
          <template #op="{ row }">
            <t-button  @click="updateUser(row.id)" size="small" variant="text" class="t-button-link">
              <t-icon name="edit-1" slot="icon"/>
              修改
            </t-button>
            <t-button theme="danger" @click="deleteUser(row.id)" size="small" variant="text" class="t-button-link">
              <t-icon name="delete" slot="icon"/>
              删除
            </t-button>
            <t-dropdown   trigger="click">
              <t-button size="small" variant="text" class="t-button-link">
                <t-icon name="chevron-right-double" slot="icon"/>
                更多
              </t-button>
              <t-dropdown-menu  slot="dropdown">
                <t-dropdown-item  @click="dialog.userId=row.id;dialog.userName=row.userName;dialog.open_reset_user_password=true" class="no-margin-padding-dropdown-item" :value="1"><t-button  size="small" variant="text" class="t-button-link">
                  <t-icon name="edit-1" slot="icon"/>
                  重置密码
                </t-button></t-dropdown-item>
                <t-dropdown-item   @click="handlerUserRole(row.id)" class="no-margin-padding-dropdown-item" :value="2"> <t-button  size="small" variant="text" class="t-button-link">
                  <t-icon name="check-circle" slot="icon"/>
                  分配角色
                </t-button></t-dropdown-item>
              </t-dropdown-menu>
              </t-dropdown>

          </template>
        </t-table>
    </div>
<!--      </t-col>-->
<!--    </t-row>-->
<!--    </div>-->
    <add-edit-user @reload="getList()" :header="dialog.header" :userId="dialog.userId" :visible.sync="dialog.open_add_edit_user" v-if="dialog.open_add_edit_user"></add-edit-user>
    <reset-user-password :visible.sync="dialog.open_reset_user_password" :userId="dialog.userId" :userName="dialog.userName" v-if="dialog.open_reset_user_password"></reset-user-password>
  </div>
</template>

<script>
import AddEditUser from './components/add-edit-user.vue'
import ResetUserPassword from './components/reset-user-password.vue'
import {
  listUser,
  changeUserStatus,
  delUser
} from "@/api/system/user";
import { treeselect, treeselectParty } from "@/api/system/dept";


export default {
  name: "user-index",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: {
    AddEditUser,
    ResetUserPassword
  },
  data() {
    return {
      deptName: "",
      activeIds: [],
      deptNameTreeValue:[],
      userId:0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: "",
        nickName: "",
        phonenumber: "",
        status: "",
        deptId: null,
        dateRange:[],
        defaultPasswdFlag: null
      },
      data: [],
      deptOptions: undefined,
      filterByText: null,
      columns: [
        // {
        //   colKey: "id",
        //   title: "用户编号",
        //   align: "center"
        // },
        {
          colKey: "userName",
          title: "登录名称",
          align: "center"
        },
        {
          colKey: "nickName",
          title: "真实姓名",
          align: "center"
        },
        {
          colKey: "roles",
          title: "角色",
          align: "center"
        },
        {
          colKey: "dept.deptName",
          title: "部门",
          align: "center"
        },
        {
          colKey: "phonenumber",
          title: "手机号",
          align: "center"
        },
        {
          colKey: "status",
          title: "状态",
          align: "center",
          width: 100
        },
        {
          colKey: "loginDate",
          title: "最后登录时间",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "center",
          width:250
        }
      ],
      dataLoading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination,pageInfo)
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList()
        },
      },
      dialog: {
        header: "",
        open_add_edit_user: false,
        open_reset_user_password: false,
        userId:0,
        userName:""
      }
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    // this.getTreeselectParty();
  },
  methods: {
    getList(){
      this.dataLoading = true;
      listUser(this.queryParams).then(
        (res) => {
          this.data = res.rows;
          this.pagination.total = res.total;
          this.dataLoading = false;
        }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    handlerUserRole(userId){
      this.$router.push(`/home/other/system/user/role/${userId}`);
    },
    onSubmit() {
      this.getList();
    },
    onReset(){
      this.queryParams.deptId = undefined;
      this.deptNameTreeValue = [];
      this.pagination.current = 1;
      this.queryParams.pageNum = 1;
      // 重置tree的高亮
      const { tree } = this.$refs;
      this.activeIds.forEach(val=>{
        tree.setItem(val, {
          actived: false,
        });
      })
      this.getList();
    },
    deleteUser(userId){
      const confirmDia = this.$dialog.confirm({
        header:"系统提示",
        body:`是否确认删除用户编号为${userId}的数据项？`,
        theme: "warning",
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          delUser(userId).then(
            (res) => {
              this.getList();
              this.$message.success("删除成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        },
      })
    },
    handleStatusChange(row) {
      const text = row.status === "1" ? "启用" : "停用";
      const status = row.status === "1" ? "0" : "1";
      const confirmDia = this.$dialog.confirm({
        header:"系统提示",
        body:`确认要${text}"${row.userName}"用户吗？`,
        theme: "warning",
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          changeUserStatus(row.id, status).then(
            (res) => {
              row.status = status;
              this.$message.success(`${text}成功`);
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });

        },
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      this.$api.system.dept.treeSelectWithUserCount().then((res) => {
        this.deptOptions = res.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    updateUser(userId){
      this.dialog.open_add_edit_user=true;
      this.dialog.header='修改用户';
      this.dialog.userId=userId;
    },
    deptNameTreeFilter(){
      if (this.deptName) {
        // 存在过滤文案，才启用过滤
        this.filterByText = (node) => {
          const rs = node.data.label.indexOf(this.deptName) >= 0;
          // 命中的节点会强制展示
          // 命中节点的路径节点会锁定展示
          // 未命中的节点会隐藏
          return rs;
        };
      } else {
        // 过滤文案为空，则还原 tree 为无过滤状态
        this.filterByText = null;
      }
    },
    handleNodeClick(content) {
      this.queryParams.deptId = content.node.data.id;
      this.getList();
      // this.handleQuery();
    },
    onActive(vals, state) {
      this.activeIds = vals;
    },
  }
}
</script>

<style scoped>
.t-dropdown__item{
  margin:0px;
  padding:0px;
}
</style>
